require(['goSwiper'], function(goSwiper) {
    var params = getUrlParams();
    var farmId = params.id;
    var navTitle = ["大宗供应","基本资料","农庄动态","农庄介绍"];
    var followSign;
    var shareSign;
    var isAttented = 'attention';
    var selfFollow;
	var action;
    var messagesPage = 1;
    var canScroll = false;
    var celebrityId;
    var isFollow;
    var shareData;  
    getData();
    //微信分享相关
	function configUrl(){
		xget(
			wxUrl+'/v3.2/login/getwxjssdkConfig',
			{
				token: token,
		        url: location.href.split('#')[0]
			},
			function(data){				
				var configUrlData = data.data;
				wx.config({
				    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				    appId: configUrlData.appId, // 必填，公众号的唯一标识
				    timestamp: configUrlData.timestamp, // 必填，生成签名的时间戳
				    nonceStr: configUrlData.nonceStr, // 必填，生成签名的随机串
				    signature: configUrlData.signature,// 必填，签名，见附录1
				    jsApiList: ['checkJsApi', 'onMenuShareTimeline',
			            'onMenuShareAppMessage', 'onMenuShareQQ',
			            'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems',
			            'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem',
			            'translateVoice', 'startRecord', 'stopRecord',
			            'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice',
			            'uploadVoice', 'downloadVoice', 'chooseImage',
			            'previewImage', 'uploadImage', 'downloadImage',
			            'getNetworkType', 'openLocation', 'getLocation',
			            'hideOptionMenu', 'showOptionMenu', 'closeWindow',
			            'scanQRCode', 'chooseWXPay', 'openProductSpecificView',
			            'addCard', 'chooseCard', 'openCard']// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				wx.ready(function(){					
					var tuijian = shareData.farm.recReason?shareData.farm.recReason:"用心提供好产品";					
					wx.onMenuShareTimeline({
					    title: '社员网农庄黄页', // 分享标题	
					    link: location.href.split('#')[0], // 分享链接
					    imgUrl: shareData.farm.coverPic?shareData.farm.coverPic:shareData.celebrity.coverPic, // 分享图标
					    success: function () { 

					    },
					    cancel: function () { 
					        // 用户取消分享后执行的回调函数
					    }
					});
					wx.onMenuShareAppMessage({
					    title: '社员网农庄黄页', // 分享标题
					    desc: shareData.farm.name+" "+tuijian, // 分享描述
					    link: location.href.split('#')[0], // 分享链接
					    imgUrl: shareData.farm.coverPic?shareData.farm.coverPic:shareData.celebrity.coverPic, // 分享图标
					    type: '', // 分享类型,music、video或link，不填默认为link
					    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
					    success: function () { 

					    },
					    cancel: function () { 
					        // 用户取消分享后执行的回调函数
					    }
					});
					wx.onMenuShareQQ({
					    title: '社员网农庄黄页', // 分享标题
					    desc:  shareData.farm.name+" "+tuijian,// 分享描述
					    link: location.href.split('#')[0], // 分享链接
					    imgUrl: shareData.farm.coverPic?shareData.farm.coverPic:shareData.celebrity.coverPic, // 分享图标
					    success: function () { 
					       // 用户确认分享后执行的回调函数
					    },
					    cancel: function () { 
					       // 用户取消分享后执行的回调函数
					    }
					});
				});
			}
		);
	}
	
    //获取详情页
    function getData() {
        xget(
        	wxUrl+'/v3.2/farm/yellowPage/detail', 
        	{
	            token: token,
	            userToken: userToken,
	            id:farmId,
	            commNum:20,
	            lat : latitude,
		    	lng : longitude
	        },
        	function(data) {
            	$('.loading_modal').hide();
	            if (data.code != 0) {
	            	promptBox(data.msg);
	            }else{
		            var result = data.data;
		            console.log(result)
		            shareData = result;
		            configUrl();
		            isFollow = result.isFollow;
		            celebrityId = result.celebrity.id;
	                var html = _.template($('#wz_tpl').html(),result);
	                $('.wz_wrapper').html(html);
	                var commentList1 = {
	                    comments : result.commentList
	                }
	                if(isFollow == '0'){
		            	$(".guanzhu img").attr('src','../static/images/keep_b.png');
                    	$(".guanzhu span").text('收藏');
		            }else{
		            	$(".guanzhu img").attr('src','../static/images/keep_r.png');
                    	$(".guanzhu span").text('已收藏');
		            }
	                if(result.goods.length == 0){
	                	$('#noGoods').show();
	                }
	                if (result.commentList.length > 5) {
	                    var html = _.template($('#wz_tpl11').html(),commentList1);
	                    $('.wz_commentList').html(html);
	                }
	                if (result.commentList.length <= 5) {
	                    var html = _.template($('#wz_tpl12').html(),commentList1);
	                    $('.wz_commentList').html(html);
	                }
	                if (result.year == 0) {
	                    $('#wz_year').hide();
	                }
					if (result.year == 0 && result.month == 0) {
	                    $('#wz_month').html('暂无');
	                }
	                if (!result.farm.acreage) {
	                    $('#wz_zzmj').html('暂无');
	                }
	
	                if (!result.farm.crop) {
	                    $('#wz_zyncp').html('暂无');
	                }
	
	                if (!result.farm.yield) {
	                    $('#wz_ncl').html('暂无');
	                }
	
	                if (!result.goodsTags) {
	                    $('#wz_cpzzR').html('暂无');
	                }
	
	                /*$('#wz_tel').on('click', function() {
//	                    hybridNW.xnativeui('tel', result.farm.telephone);
	                });*/
	                if (result.farm.nature == 0) {
	                    $('#wz_gsxz').text('个人');
	                }
	                if (result.farm.nature == 1) {
	                    $('#wz_gsxz').text('企业');
	                }
	                if (result.farm.nature == null) {
	                    $('#wz_gsxz').text('暂无');
	                }
	                if (result.celebrity.proxy == 1) {
	                    $('#wz_noStory').hide();
	                    $('#wz_storyCtn').html(result.farm.proxyIntroduction);
	                    $('.swiper-wrapper').height($('.swiper-slide-active').height());
	                }
	                if (result.celebrity.proxy == 0) {
	                    $('#wz_noStory').hide();
	                    if (result.farm.introduction) {
	                        $('<p style="text-align:center;">'+result.farm.introduction+'</p>').appendTo($('#wz_storyCtn'));
	                        $('.swiper-wrapper').height($('.swiper-slide-active').height());
	                    }
	                    if (result.farm.photos) {
	                        for (var i = 0; i < result.farm.photos.length; i++) {
	                            $('<p><img src="'+result.farm.photos[i]+'"></p>').appendTo($('#wz_storyCtn'));
	                        }
	                        $('.swiper-wrapper').height($('.swiper-slide-active').height());
	                        
	                    }
	                }
	                if (result.celebrity.proxy == 2) {
	                    $('.wz_noStory').show();
	                    $('.swiper-wrapper').height($('.swiper-slide-active').height());
	
	                }
	                if (result.goodsTags) {
	                    for(var i = 0, length1 = result.goodsTags.length; i < length1; i++){
	                        if (result.goodsTags[i] == '1') {
	                            $('<div class="wz_cpzzLi"><div class="wz_cpzzLiIcon"><img src="../static/images/wz/yellow/yj.png" alt=""></div><div class="wz_cpzzLiText">有机</div></div>').appendTo($('#wz_cpzzR'));
	                        }
	                        if (result.goodsTags[i] == '2') {
	                            $('<div class="wz_cpzzLi"><div class="wz_cpzzLiIcon"><img src="../static/images/wz/yellow/ls.png" alt=""></div><div class="wz_cpzzLiText">绿色</div></div>').appendTo($('#wz_cpzzR'));
	                        }
	                        if (result.goodsTags[i] == '3') {
	                            $('<div class="wz_cpzzLi"><div class="wz_cpzzLiIcon"><img src="../static/images/wz/yellow/wgh.png" alt=""></div><div class="wz_cpzzLiText">无公害</div></div>').appendTo($('#wz_cpzzR'));
	                        }  
	                    }
	                }
	                if (result.celebrity.idCard == 1) {
	                    $('#wz_idCard').show();
	                }
	                if (result.celebrity.bankCard == 1) {
	                    $('#wz_bankCard').show();
	                }
	                if (result.farm.telephone) {
	                    $('#wz_phoneCard').show();
	                }
	                
	                //添加收藏、取消收藏
	                $('.guanzhu').click(function(){
	                	if(vLoginClick()){
	                		if(isFollow == '0'){
		                		xget(
			                    	wxUrl+'/v3.2/collection/farm', 
			                    	{
			                    		token: token,
			                    		userToken: userToken,
					                    action: 1,
					                    farmId: farmId
				                    }, 
				                    function (data) {
			                            if (data.code != 0) {
			                                promptBox(data.msg);
			                                if(10200 == data.code){
												window.location.href="../userCenter/paymentPassword/signIn.html";
											}
			                            }else{
			                            	var success = data.data.success;
			                            	if(success){
				                            	$(".guanzhu img").attr('src','../static/images/keep_r.png');
				                            	$(".guanzhu span").text('已收藏');
				                            	promptBox('收藏成功！');
				                            	isFollow = '1';
			                            	}
			                            }  
				                    }
				                );
		                	}else{
		                		xget(
			                    	wxUrl+'/v3.2/collection/farm', 
			                    	{
			                    		token: token,
			                    		userToken: userToken,
					                    action: 0,
					                    farmId: farmId
				                    }, 
				                    function (data) {
			                            if (data.code != 0) {
			                                promptBox(data.msg);
			                                if(10200 == data.code){
												window.location.href="../userCenter/paymentPassword/signIn.html";
											}
			                            }else{
			                            	var success = data.data.success;
			                            	if(success){
				                            	$(".guanzhu img").attr('src','../static/images/keep_b.png');
				                            	$(".guanzhu span").text('收藏');
				                            	promptBox('已取消收藏！');
				                            	isFollow = '0';
			                            	}
			                            }  
				                    }
				                );
		                	}
	                	}
	                });

	                //获取评论
	                setTimeout(function () {
	                    xget(
	                    	wxUrl+'/v3.2/farm/yellowPage/getCommentList', 
	                    	{
	                    		token: token,
			                    id: farmId,
			                    pageNo: 1,
			                    pageSize: 20
	                    	}, 
		                    function(data) {
		                        if (data.code != 0) {
		                            promptBox(data.msg);
		                        }else{
		                        	var result = data.data;
		                            if (result.comments) {
		                                $('.wz_commentTop').show();
		                                $('.wz_noComment').hide();
		                                $('.wz_commentTem').show();
		                                var html = _.template($('#wz_tpl2').html(),result);
		                                $('.wz_commentTem').html(html);
		                                $('#wz_allComment').on('click', function() {
		                                    $('.wz_commentTem').show();
		                                    $('.swiper-wrapper').height($('.swiper-slide-active').height());
		                                });
		                                var imgLength = $('.wz_img').length;
		                                for (var i = 0; i < imgLength; i++) {
		                                    if ( $('.wz_img')[i].src.indexOf('.html') != -1 ) {
		                                        $('.wz_img')[i].setAttribute('style', 'display : none');
		                                    }
		                                }
		                            }else{
		                                $('.wz_commentTop').hide();
		                                $('.wz_noComment').show();
		                                $('.wz_commentTem').hide();
		                                $('.swiper-wrapper').height($('.swiper-slide-active').height());
		                            }
		                        }
		                    }
		                );
	                },200);
	               
	                getEvents();
	                //获取庄主动态
	                function getEvents() {
	                    xget(
	                    	wxUrl+'/v3.2/farm/yellowPage/messageList', 
	                    	{
	                    		token: token,
			                    celebrityId:celebrityId,
			                    pageNo:messagesPage,
			                    pageSize:5
		                    }, 
		                    function(data) {
	                            if (data.code != 0) {
	                                promptBox(data.msg);
	                            }else{
	                            	var result = data.data;
	                            	if (result.messages) {
		                                $('.wz_nodt').hide();
		                                canScroll = true;
		                                var html = _.template($('#wz_tpl3').html(),result);
		                                $('.wz_dt').append(html);
		                                $('.swiper-wrapper').height( $('.swiper-slide-active').height());
		                                $('.wz_dtRList').on('click', function() {
		                                    var index2 = $(this).index();
		                                    var index = $(this).parents('.wz_dtCtn').index();
		                                    var dynamicType = result.messages[index2].messageList[index].type;
		                                    var dynamicId = result.messages[index2].messageList[index].id;
		                                });
		                                $(window).scroll(function(event) {
		                                    var scrollTop = $(this).scrollTop();
		                                    var scrollHeight = $(document).height();
		                                    var windowHeight = $(this).height();
		                                    if(scrollTop + windowHeight == scrollHeight){
		                                        messagesPage++;
		                                        if (messagesPage == result.totalPage + 1) {
		                                            canScroll = false;
		                                            promptBox('没有更多数据了！');
		                                        }else {
		                                            if (canScroll) {
		                                                getEvents();
		                                            }
		                                        }
		                                    }
		                                });
		                            }else{
			                            $('.wz_nodt').show();
			                        }
			                    }
		                    }
		                );
	                }
	                //tab切换
	                var swiper = new Swiper('.swiper-container', {
	                    pagination: '.swiper-pagination',
	                    paginationClickable: true,
	                    autoplayDisableOnInteraction: false,
	                    autoHeight:true,
	                    paginationBulletRender: function(index, className) {
	                        if (index == navTitle.length - 1) {
	                            return '<div class="' + className + ' paginationLast"><span>' + navTitle[index] + '</span><div class="wz_bottom"></div></div>';
	                        }
	                        return '<div class="' + className + '"><span>' + navTitle[index] + '</span><div class="wz_bottom"></div></div>';
	                    }
	                });
	                //tab滚动特殊效果
	                var h2 = $('.swiper-pagination').offset().top;
	                var eventOH = $('.wz_dt').offset().top;
	                var eventH = $('.wz_dt').height();
	                $(window).scroll(function(event) {
	                    var h = $(this).scrollTop();
	                    if(h > h2){
	                        $('.swiper-pagination').addClass('wz_fix');
	                        $('.swiper-container').addClass('wz_margin');
	                    }
	                    if (h < h2) {
	                        $('.swiper-pagination').removeClass('wz_fix');
	                        $('.swiper-container').removeClass('wz_margin');
	                    }
	                });
	            }
				$('.left_pic').on('click', function() {
					var id = $(this).attr("goodsId");
					window.location.href = '../bigSupply/bs_detail.html?id='+id;
				});
        })
    }
});
// 为可控制返回指定页面所有添加pushState
history.pushState({}, document.title, null);
pushVHistory();
window.addEventListener("popstate", function() {
    // 跳转到订单列表页面
	goBackVHistory();
});